package space.xxhui.javatts.service.impl;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import space.xxhui.javatts.base.constants.LanguageConstants;
import space.xxhui.javatts.dao.TtsRecordDao;
import space.xxhui.javatts.dto.TextToSpeechDto;
import space.xxhui.javatts.entity.TtsRecord;
import space.xxhui.javatts.service.TtsService;
import space.xxhui.javatts.tts.engine.Engine;

import javax.annotation.Resource;
import java.io.File;

/**
 * @author HitvzByHui
 * date 2021-03-29
 */
@Service
public class TtsServiceImpl implements TtsService {

    @Autowired
    private TtsRecordDao ttsRecordDao;
    @Resource(name = "cantoneseConvertEngine")
    private Engine cantoneseConvertEngine;

    @Override
    public String convert(TextToSpeechDto dto) {
        String cachePath = getCachePath(dto);
        if (StringUtils.isEmpty(cachePath)) {
            saveToCache(dto, textToSpeech(dto));
        }
        return dto.getText();
    }

    public String textToSpeech(TextToSpeechDto dto) {
        if(dto.getLanguage().equals(LanguageConstants.CANTONESE)){
            cantoneseConvertEngine.convert(dto.getText());
        }

        return dto.getText();
    }

    public boolean saveToCache(TextToSpeechDto dto, String path) {
        String md5 = DigestUtils.md5Hex(dto.getText());
        TtsRecord record = ttsRecordDao.getRecord(md5, dto.getLanguage());
        if (record == null) {
            record = new TtsRecord();
            record.setText(dto.getText());
            record.setLanguage(dto.getLanguage());
            record.setSpeechFilePath(path);
            record.setTextMd5(md5);
            return ttsRecordDao.insert(record) > 0;
        }
        return false;
    }

    public String getCachePath(TextToSpeechDto dto) {
        if (1 + 1 == 2) {
            return "";
        }
        //todo 暂时注释这部分逻辑
        String md5 = DigestUtils.md5Hex(dto.getText());
        TtsRecord record = ttsRecordDao.getRecord(md5, dto.getLanguage());
        if (record == null) {
            return "";
        }
        //校验文件是否存在，不存在，则删除记录
        String filePath = record.getSpeechFilePath();
        if (StringUtils.isEmpty(filePath)) {
            ttsRecordDao.delete(record.getId());
            return "";
        }
        File file = new File(filePath);
        if (file.isDirectory() || !file.exists()) {
            ttsRecordDao.delete(record.getId());
            return "";
        }
        return record.getSpeechFilePath();
    }


}
